<template>
  <a-modal
    :zIndex="1000"
    :visible="visible"
    @cancel="cancelClick"
    :footer="null"
    width="660px"
    :mask-closable="false"
  >
    <template #title>
      <span style="margin-right: 10px">上传文件夹</span>
      <a-popover placement="top">
        <template #content>
          <div>
            <div class="model_text model_text_one">
              视频格式: mov/mp4/3gp(文件≤1G、时长≤60分钟、分辨率480p~4k)
            </div>
            <div class="model_text">
              图片格式: jpg/jpeg/png,图片尺寸50~8000,单张图片不可大于20M
            </div>
            <div class="model_text">
              音频格式: mp3/m4a/aac/wav(文件≤1G、时长≤60分钟)
            </div>
          </div>
        </template>
        <question-circle-outlined style="margin-left: 3px" />
      </a-popover>
    </template>

    <div v-show="Allin_up" style="margin-top: 40px"></div>
    <a-upload
      class="model_upload"
      v-show="Allin_up"
      :customRequest="customRequest"
      v-model:file-list="fileList"
      :max-count="10"
      :before-upload="beforeUpload"
      :multiple="true"
      name="file"
      :directory="directory"
      accept=".mp4,.mov,.3gp,.mp3,.m4a,.aac,.jpg,.jpeg,.png,.wav,audio/wav"
      list-type="picture-card"
    >
      <div class="model_upload_text">
        <cloud-upload-outlined />
        <div>
          <div>上传文件夹</div>
        </div>
      </div>
    </a-upload>

    <div class="yulan_box">
      <!-- 图片 -->
      <div v-if="!Allin_up && All_img.length > 0" class="Allin_B">
        <div class="All_icon">
          <cu-icon type="icon-wenjianjia1" />

          <!-- 已上传 -->
          <div class="up_fin" v-if="img_up_finish == true">
            <a-tag color="success">已上传</a-tag>
          </div>
        </div>
        <!-- 进度条  上传中  -->
        <div class="progress_item" v-if="img_up_ing == true && loading">
          <a-progress
            :percent="100"
            :showInfo="false"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>
        <div class="Allin_T">
          <div class="Allin_T_left">{{ mater_name }}-图片</div>

          <div class="Allin_T_right">
            <delete-outlined
              class=""
              v-if="!loading"
              @click="del_item('image')"
            />
          </div>
        </div>
      </div>
      <!-- 视频 -->
      <div v-if="!Allin_up && All_video.length > 0" class="Allin_B">
        <div class="All_icon">
          <cu-icon type="icon-wenjianjia1" />

          <!-- 已上传 -->
          <div class="up_fin" v-if="video_up_finish == true">
            <a-tag color="success">已上传</a-tag>
          </div>
        </div>

        <!-- 进度条  上传中  -->
        <div class="progress_item" v-if="video_up_ing == true && loading">
          <a-progress
            :percent="100"
            :showInfo="false"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>
        <div class="Allin_T">
          <div class="Allin_T_left">{{ mater_name }}-视频</div>
          <div class="Allin_T_right">
            <delete-outlined
              class=""
              v-if="!loading"
              @click="del_item('video')"
            />
          </div>
        </div>
      </div>

      <!-- 音频 -->
      <div v-if="!Allin_up && All_audio.length > 0" class="Allin_B">
        <div class="All_icon">
          <cu-icon type="icon-wenjianjia1" />

          <!-- 已上传 -->
          <div class="up_fin" v-if="audio_up_finish == true">
            <a-tag color="success">已上传</a-tag>
          </div>
        </div>

        <!-- 进度条  上传中  -->
        <div class="progress_item" v-if="audio_up_ing == true && loading">
          <a-progress
            :percent="100"
            :showInfo="false"
            type="line"
            size="small"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            status="active"
          />
        </div>

        <div class="Allin_T">
          <div class="Allin_T_left">{{ mater_name }}-音频</div>
          <div class="Allin_T_right">
            <delete-outlined
              class=""
              v-if="!loading"
              @click="del_item('audio')"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="footer">
      <a-space>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          :disabled="TwoAllNum.length == 0"
          @click="saveFn"
          >开始上传</a-button
        >
      </a-space>
    </div>

    <div class="baseModel">
      <a-modal
        :getContainer="'.baseModel'"
        v-model:visible="canel_visible"
        @ok="canel_handleOk"
        :zIndex="2000"
        :style="{ border: 'none' }"
      >
        <div class="cancel_content" style="padding-top: 30px">
          <div style="font-weight: bold; font-size: 16px; margin-right: 10px">
            <info-circle-outlined style="color: #f7a726" />
            提示
          </div>
          <div style="margin-top: 10px">
            当前页面正在上传中，直接离开数据不会保存和更新
          </div>
        </div>
        <template #footer>
          <a-button style="border-radius: 5px" @click="gocanel"
            >确认返回</a-button
          >
          <a-button
            style="border-radius: 5px"
            type="primary"
            @click="canel_handleOk"
            >留在当前页</a-button
          >
        </template>
      </a-modal>
    </div>
  </a-modal>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  watch,
  onUnmounted,
  computed,
  createVNode,
} from "vue";
import {
  CloudUploadOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message, Form, notification, Modal } from "ant-design-vue";
import request from "../../../../common/utils/request";
import utils from "@/common/utils/utils.js";
import axios from "axios";
import defaultSetting from "@/common/utils/defaultSetting.js";
import store from "@/store";
import { upload } from "@/common/utils/uploader/index";

const useForm = Form.useForm;

export default defineComponent({
  name: "PreviewImg",
  components: {
    CloudUploadOutlined,
    DeleteOutlined,
    QuestionCircleOutlined,
    ExclamationCircleOutlined,
  },
  props: {
    activeKey: {
      type: String,
      default: "",
    },
    directory: {
      type: Boolean,
      default: false,
    },
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "",
    },
    AllData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    fileData: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      loading: false,
      fileList: [],
      fileData: {},
      start: "",
      end: "",
      type: "",
      imageWidth: 0,
      imageHeight: 0,
      Allin_up: true,
      All_img: [],
      All_video: [],
      All_audio: [],
      duan_show: false,
      AllNum: [],
      mater_name: "",
      typeArr: [],
      TwoAllNum: [],
      newMaterList: {
        image_id: 0,
        video_id: 0,
        audio_id: 0,
      },
      queryData: {
        files: [],
      },
      allImagesFinished: false,
      allVideosFinished: false,
      allAudiosFinished: false,
      img_up_ing: false,
      img_up_finish: false,
      video_up_ing: false,
      video_up_finish: false,
      audio_up_ing: false,
      audio_up_finish: false,
      ispollInterval: false,
      BASE_URL: "",
      shouldContinuePolling: true,
      upload_finish: [],
      img_finish: [],
      video_finish: [],
      audio_finish: [],
      is_over: false,
      canel_visible: false,
      is_goon: true,
    });

    const work_ai_config = computed(() => {
      return store?.state?.shotstack?.work_ai_config || {};
    });

    const isAlionline = computed(() => {
      return work_ai_config.value?.shotstack_driver == "alionline";
    });

    const isOss = computed(() => {
      return work_ai_config.value?.upload_driver == "oss";
    });

    const getFileType = (file) => {
      // 如果 file.type 不为空，直接返回
      if (file.file.type) return file.file.type;

      // 基于扩展名推测 MIME 类型
      const extension = file.file.name.split('.').pop().toLowerCase();
      const mimeTypes = {
        mov: 'video/quicktime',
        mp4: 'video/mp4',
        '3gp': 'video/3gpp',
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        png: 'image/png',
        mp3: 'audio/mpeg',
        m4a: 'audio/mp4',
        wav: 'audio/wav',
        ogg: 'audio/ogg',
        pcm: 'audio/pcm',
      };
      return mimeTypes[extension] || '';
    };

    // 手动上传
    const customRequest = (file) => {
      state.TwoAllNum.push(file.file);
      state.queryData.files.push(file.file);
      state.mater_name = file.file.webkitRelativePath.split("/")[0];
      state.Allin_up = false;



      state.typeArr.push(getFileType(file).split("/")[0]);
      const uniqueTypeArr = [...new Set(state.typeArr)];
      state.typeArr = uniqueTypeArr;

      const modeltype = file.file.type.split("/")[0];
      const url = URL.createObjectURL(file.file);

      if (modeltype == "image") {
        state.All_img.push({
          material_name: file.file.name,
          material_size: file.file.size,
          material_type: "image",
          material_url: url,
          up_ing: false,
          up_finish: false,
          id: file.file.uid,
        });
      } else if (modeltype == "video") {
        state.All_video.push({
          material_name: file.file.name,
          material_size: file.file.size,
          material_type: "video",
          material_url: url,
          up_ing: false,
          up_finish: false,
          id: file.file.uid,
        });
      } else if (modeltype == "audio") {
        state.All_audio.push({
          material_name: file.file.name,
          material_size: file.file.size,
          material_type: "audio",
          material_url: url,
          up_ing: false,
          up_finish: false,
          id: file.file.uid,
        });
      }
    };

    // 开始上传
    const saveFn = async () => {
      if (state.TwoAllNum.length == 0) {
        return message.warn("请上传文件夹");
      }

      let oss_config;
      async function getOss_config() {
        const response = await request.post(
          "/work_ai",
          "/upload/oss/config/ststoken"
        );
        if (response.sts) {
          oss_config = response.sts;
          const nowTimestamp = Date.now();

          const expiresAtTimestamp =
            nowTimestamp + response.sts.duration * 1000;
          const stsToken_config = {
            stsToken: response.sts.stsToken,
            duration: response.sts.duration,
            FailDate: expiresAtTimestamp,
          };

          localStorage.setItem(
            "stsToken_config",
            JSON.stringify(stsToken_config)
          );
        }
      }

      async function RegetOss_config() {
        const response = await request.post(
          "/work_ai",
          "/upload/oss/config/ststoken",
          {
            isRefresh: "1",
          }
        );
        if (response.sts) {
          oss_config = response.sts;
          const nowTimestamp = Date.now();
          const expiresAtTimestamp =
            nowTimestamp + response.sts.duration * 1000;
          const stsToken_config = {
            stsToken: response.sts.stsToken,
            duration: response.sts.duration,
            FailDate: expiresAtTimestamp,
          };

          localStorage.setItem(
            "stsToken_config",
            JSON.stringify(stsToken_config)
          );
        }
      }

      if (
        work_ai_config.value?.shotstack_driver == "alionline" ||
        work_ai_config.value?.upload_driver == "oss"
      ) {
        await getOss_config();

        const newoss_config = JSON.parse(
          localStorage.getItem("stsToken_config")
        );

        // token 过期处理
        if (newoss_config == null) {
          await RegetOss_config();
        }
        const nowTime = Date.now();

        if (newoss_config.FailDate < nowTime) {
          await RegetOss_config();
        }
      }

      state.BASE_URL = defaultSetting.requestDomain;
      if (process.env.NODE_ENV === "development") {
        state.BASE_URL = state.BASE_URL + "/api";
      }
      if (state.AllNum.length == state.TwoAllNum.length) {
        console.log(state.typeArr,'state.typeArr');
        let params = {
          merchant_library_id:
            props.activeKey == 2 ? 0 : props.AllData.merchant_library_id,
          group_id: props.activeKey == 2 ? 0 : props.AllData.group_id,
          folder_name: state.mater_name,
          folder_type: state.typeArr.join("_"),
        };
        request
          .post("/work_ai", "/user/shotstack/folder/create", params)
          .then((res) => {
            state.newMaterList.image_id = res.result.image;
            state.newMaterList.video_id = res.result.video;
            state.newMaterList.audio_id = res.result.audio;
            state.loading = true;

            // 控制并发数量的函数
            // async function processQueue(queue, concurrency) {
            //   const runningTasks = new Set();
            //   const results = [];

            //   const addTask = async () => {
            //     if (queue.length === 0) {
            //       return;
            //     }

            //     const task = queue.shift();
            //     const promise = task()
            //       .then((res) => {
            //         results.push(res);
            //         runningTasks.delete(promise);
            //         addTask();
            //       })
            //       .catch((error) => {
            //         results.push(null);
            //         runningTasks.delete(promise);
            //         addTask();
            //       });

            //     runningTasks.add(promise);
            //   };

            //   for (let i = 0; i < concurrency; i++) {
            //     addTask();
            //   }

            //   while (runningTasks.size > 0 || queue.length > 0) {
            //     await Promise.race(runningTasks);
            //   }

            //   return results;
            // }

            let upDataList = state.queryData.files.map((item) => ({
              ...item,
              name: item.name,
              id: item.uid,
              state: 0,
              percent: 0,
              iscancel: false,
            }));

            // 将上传数据 同步至vuex
            store.dispatch("SetUpDateList", upDataList);

            for (let i = 0; i < state.queryData.files.length; i++) {
              const file = state.queryData.files[i];
              request.post("/work_ai", "/material/get/capacity").then((res) => {
                const remainingCapacity = parseInt(res.result.remainingCapacity, 10);

                if (remainingCapacity < file.size) {
                  message.error(`存储空间不足，无法上传文件：${file.name}`);
                } else {
                  // ------------------------- Oss ---------------------------
                  let config;
                  async function Oss_Upload() {
                    let Now_type = file.type.split("/")[0];
                    let Now_merchantID;
                    switch (Now_type) {
                      case "image":
                        Now_merchantID = state.newMaterList.image_id;
                        state.img_up_ing = true;
                        break;
                      case "video":
                        Now_merchantID = state.newMaterList.video_id;
                        state.video_up_ing = true;
                        break;
                      case "audio":
                        Now_merchantID = state.newMaterList.audio_id;
                        state.audio_up_ing = true;
                        break;
                      default:
                        Now_merchantID = state.newMaterList.video_id;
                        state.video_up_ing = true;
                        break;
                    }

                    await request
                      .get("/work_ai", "/material/upload/info", {
                        merchant_folder_statck_id: Now_merchantID,
                        upload_from: "",
                        number: "1",
                      })
                      .then((res) => {
                        // if (res.code == 1001) {
                        //   noenzu.value = true;
                        // }
                        if (
                          res.result.pointInfo.current >=
                          res.result.pointInfo.consumes
                        ) {
                          if (res.result.free_send_text == "赠送套餐") {
                            if (file.size > res.result.fileMaxSize) {
                              message.error(res.result.fileMaxSizeErr);
                              return;
                            }
                          }
                          // 可选的配置对象
                          config = {
                            SetUploadPath: res.result.upload_path,
                            oss_config: oss_config,
                          };
                        } else {
                          if (state.is_goon) {
                            state.is_goon = false;
                            state.queryData.files = [];
                            state.img_up_finish = false;
                            state.video_up_finish = false;
                            state.audio_up_finish = false;
                            state.All_img = [];
                            state.All_video = [];
                            state.All_audio = [];
                            state.Allin_up = true;
                            state.duan_show = false;
                            state.loading = false;
                            message.warning(
                              `${res.result.pointInfo.name}不足, 请充值`
                            );
                          }
                        }
                      });

                    if (state.is_goon) {
                      // 开始上传
                      const Oss_result = await upload(file, config);

                      let up_paramas = {
                        merchant_folder_statck_id: Now_merchantID,
                        material_type: Now_type,
                        material_name: Oss_result.name,
                        material_url: Oss_result.fileUrl,
                        material_size: file.size,
                      };

                      if (!state.is_over) {
                        request
                          .post("/work_ai", "/user/mobile/media", up_paramas)
                          .then((res) => {
                            state.upload_finish.push(res.result);
                            switch (res.material_type) {
                              case "image":
                                state.img_finish.push(res.result);
                                break;
                              case "video":
                                state.video_finish.push(res.result);
                                break;
                              case "audio":
                                state.audio_finish.push(res.result);
                                break;
                            }

                            const totalImageFiles =
                              state.queryData.files.filter(
                                (item) => item.type.split("/")[0] == "image"
                              ).length;

                            if (state.img_finish.length == totalImageFiles) {
                              state.img_up_ing = false;
                              state.img_up_finish = true;
                            }

                            const totalVideoFiles =
                              state.queryData.files.filter(
                                (item) => item.type.split("/")[0] == "video"
                              ).length;

                            if (state.video_finish.length == totalVideoFiles) {
                              state.video_up_ing = false;
                              state.video_up_finish = true;
                            }

                            const totalAudioFiles =
                              state.queryData.files.filter(
                                (item) => item.type.split("/")[0] == "audio"
                              ).length;

                            if (state.audio_finish.length == totalAudioFiles) {
                              state.audio_up_ing = false;
                              state.audio_up_finish = true;
                            }
                            // 全部上传成功
                            if (
                              state.upload_finish.length ==
                              state.queryData.files.length
                            ) {
                              state.queryData.files = [];
                              state.img_up_finish = false;
                              state.video_up_finish = false;
                              state.audio_up_finish = false;
                              message.success("上传完成!");
                              state.All_img = [];
                              state.All_video = [];
                              state.All_audio = [];
                              state.Allin_up = true;
                              state.duan_show = false;
                              state.loading = false;
                              emit("onSubmit_All");
                            }
                          })
                          .catch((error) => {
                            message.error("上传错误, 请稍后重试");
                          });
                      }
                    }
                  }
                  // ------------------------- Cos ---------------------------
                  async function Cos_Upload(file) {
                    const mimeType = file.type.split("/")[0];
                    let merchant_id;
                    switch (mimeType) {
                      case "image":
                        merchant_id = state.newMaterList.image_id;
                        state.img_up_ing = true;
                        break;
                      case "video":
                        merchant_id = state.newMaterList.video_id;
                        state.video_up_ing = true;
                        break;
                      case "audio":
                        merchant_id = state.newMaterList.audio_id;
                        state.audio_up_ing = true;
                        break;
                      default:
                        break;
                    }
                    const formData = new FormData();
                    formData.append("file", file);
                    formData.append("type", mimeType);
                    formData.append("scene", mimeType);
                    formData.append("merchant_folder_statck_id", merchant_id);
                    formData.append("org_id", utils.getOrgId());
                    formData.append("user_token", utils.getToken());
                    formData.append(
                      "cur_env",
                      utils.isMobile()
                        ? "h5"
                        : import.meta.env.ELECTRON
                        ? "desktop"
                        : "pc"
                    );
                    formData.append("team_id", utils.getCurrentTeam());
                    axios({
                      method: "post",
                      url: `${state.BASE_URL}/work_ai/material/upload`,
                      data: formData,
                      headers: {
                        "Content-Type": "multipart/form-data",
                        "Org-Token": utils.getToken(),
                      },
                    })
                      .then((response) => {
                        if (response?.data?.data?.errorData.length > 0) {
                          // 错误处理
                          notification.warn({
                            message: response.data.data.errorData[0],
                            duration: 2,
                          });
                          state.loading = false;
                          state.All_img = [];
                          state.All_video = [];
                          state.All_audio = [];
                          state.img_up_ing = false;
                          state.video_up_ing = false;
                          state.audio_up_ing = false;
                          state.queryData.files = [];
                          state.Allin_up = true;
                        } else {
                          let pollInterval;
                          const startPolling = () => {
                            pollInterval = setInterval(() => {
                              request
                                .get("/work_ai", "/material/upload/status", {
                                  taskId:
                                    response.data?.data?.returnData[0].taskId,
                                })
                                .then((res) => {
                                  if (res?.status == 1) {
                                    // 继续轮询
                                  } else if (res?.status == 2) {
                                    state.shouldContinuePolling = false; // 设置标志以停止轮询
                                    clearInterval(pollInterval); // 清除定时器
                                    switch (mimeType) {
                                      case "image":
                                        state.All_img.forEach((item) => {
                                          if (item.id == file.uid) {
                                            item.up_ing = false;
                                            item.up_finish = true;
                                          }
                                        });
                                        state.allImagesFinished =
                                          state.All_img.every(
                                            (item) => item.up_finish === true
                                          );
                                        if (state.allImagesFinished == true) {
                                          state.img_up_ing = false;
                                          state.img_up_finish = true;
                                        }
                                        break;
                                      case "video":
                                        state.All_video.forEach((item) => {
                                          if (item.id == file.uid) {
                                            item.up_ing = false;
                                            item.up_finish = true;
                                          }
                                        });
                                        state.allVideosFinished =
                                          state.All_video.every(
                                            (item) => item.up_finish === true
                                          );
                                        if (state.allVideosFinished == true) {
                                          state.video_up_ing = false;
                                          state.video_up_finish = true;
                                        }

                                        break;
                                      case "audio":
                                        state.All_audio.forEach((item) => {
                                          if (item.id == file.uid) {
                                            item.up_ing = false;
                                            item.up_finish = true;
                                          }
                                        });
                                        state.allAudiosFinished =
                                          state.All_audio.every(
                                            (item) => item.up_finish === true
                                          );
                                        if (state.allAudiosFinished == true) {
                                          state.audio_up_ing = false;
                                          state.audio_up_finish = true;
                                        }
                                        break;
                                      default:
                                        break;
                                    }
                                    let allTypesFinished = true;
                                    state.typeArr.forEach((item) => {
                                      switch (item) {
                                        case "image":
                                          if (!state.allImagesFinished) {
                                            allTypesFinished = false;
                                          }
                                          break;
                                        case "video":
                                          if (!state.allVideosFinished) {
                                            allTypesFinished = false;
                                          }
                                          break;
                                        case "audio":
                                          if (!state.allAudiosFinished) {
                                            allTypesFinished = false;
                                          }
                                          break;
                                        default:
                                          break;
                                      }
                                    });

                                    // 如果所有类型的文件都上传完成，则触发事件
                                    if (allTypesFinished) {
                                      state.allImagesFinished = false;
                                      state.allVideosFinished = false;
                                      state.allAudiosFinished = false;
                                      state.img_up_ing = false;
                                      state.img_up_finish = false;
                                      state.video_up_ing = false;
                                      state.video_up_finish = false;
                                      state.audio_up_ing = false;
                                      state.audio_up_finish = false;
                                      state.AllNum = [];
                                      state.All_img = [];
                                      state.All_video = [];
                                      state.All_audio = [];
                                      state.typeArr = [];
                                      state.TwoAllNum = [];
                                      state.queryData.files = [];
                                      (state.Allin_up = true),
                                        (state.loading = false);
                                      (state.newMaterList = {
                                        image_id: 0,
                                        video_id: 0,
                                        audio_id: 0,
                                      }),
                                        emit("onSubmit_All");
                                    }
                                  } else if (res.status == 3) {
                                    // 上传失败  停止轮训
                                    state.shouldContinuePolling = false; // 设置标志以停止轮询
                                    clearInterval(pollInterval); // 清除定时器
                                    state.loading = false;
                                    state.img_up_ing = false;
                                    state.video_up_ing = false;
                                    state.audio_up_ing = false;
                                  }
                                })
                                .catch((error) => {
                                  clearInterval(pollInterval);
                                  state.allImagesFinished = false;
                                  state.allVideosFinished = false;
                                  state.allAudiosFinished = false;
                                  state.img_up_ing = false;
                                  state.img_up_finish = false;
                                  state.video_up_ing = false;
                                  state.video_up_finish = false;
                                  state.audio_up_ing = false;
                                  state.audio_up_finish = false;
                                  state.AllNum = [];
                                  state.All_img = [];
                                  state.All_video = [];
                                  state.All_audio = [];
                                  state.typeArr = [];
                                  state.TwoAllNum = [];
                                  state.queryData.files = [];
                                  (state.Allin_up = true),
                                    (state.loading = false);
                                  state.newMaterList = {
                                    image_id: 0,
                                    video_id: 0,
                                    audio_id: 0,
                                  };
                                  emit("onSubmit_All");
                                });
                            }, 2000);
                          };
                          startPolling();
                        }
                      })
                      .catch((error) => {
                        message.error("上传文件失败, 请重新上传");
                        state.allImagesFinished = false;
                        state.allVideosFinished = false;
                        state.allAudiosFinished = false;
                        state.img_up_ing = false;
                        state.img_up_finish = false;
                        state.video_up_ing = false;
                        state.video_up_finish = false;
                        state.audio_up_ing = false;
                        state.audio_up_finish = false;
                        state.AllNum = [];
                        state.All_img = [];
                        state.All_video = [];
                        state.All_audio = [];
                        state.typeArr = [];
                        state.TwoAllNum = [];
                        state.queryData.files = [];
                        (state.Allin_up = true), (state.loading = false);
                        state.newMaterList = {
                          image_id: 0,
                          video_id: 0,
                          audio_id: 0,
                        };
                        emit("onSubmit_All");
                      });
                  }

                  if (isAlionline.value || isOss.value) {
                    // 阿里云上传
                    Oss_Upload();
                  } else {
                    Cos_Upload();
                  }
                }
              });
            }
          });
      }
    };

    const beforeUpload = async (file) => {
      state.AllNum.push(file);
      let type = file.type.split("/")[0];
      if (type === "video") {
        return new Promise((resolve) => {
          const isLt1G = file.size / 1024 / 1024 / 1024 < 1;
          if (!isLt1G) {
            message.error("视频文件不可大于 1GB!");
            resolve(false);
            return;
          }
          const video = document.createElement("video");
          const blobURL = URL.createObjectURL(file);
          video.src = blobURL;
          video.onloadedmetadata = () => {
            const duration = video.duration;
            const width = video.videoWidth;
            const height = video.videoHeight;

            if (duration > 3600) {
              message.error("视频文件不能大于 60 分钟时长!");
              resolve(false);
              return;
            }


            if (width > 4096 || height > 4096) {
              message.error("视频最大不能超过 4096px!");
              resolve(false);
              return;
            }

            resolve(true);
          };
        });
      } else if (type == "image") {
        const isLt2M = file.size / 1024 / 1024 < 20;
        let w = 0,
          h = 0;
        let reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          const image = new Image();
          image.src = reader.result;
          image.onload = () => {
            w = image.width;
            h = image.height;
            state.imageWidth = image.width;
            state.imageHeight = image.height;
            if (w <= 49 || h <= 49) {
              state.fileList = state.fileList.filter(
                (item) => item.uid !== file.uid
              );
              message.error("图片宽度不能小于50px");
              return false;
            } else if (w >= 8000 || h >= 8000) {
              state.fileList = state.fileList.filter(
                (item) => item.uid !== file.uid
              );
              message.error("图片宽度不能大于8000px");
              return false;
            }
            if (!isLt2M) {
              message.error("文件不可大于 20M!");
              return false;
            }
            return true;
          };
        };
      }
    };

    const canel_handleOk = () => {
      state.canel_visible = false;
    };

    const gocanel = () => {
      state.canel_visible = false;
      state.All_img = [];
      state.All_video = [];
      state.All_audio = [];
      state.Allin_up = true;
      state.duan_show = false;
      state.loading = false;
      state.is_over = true;
      emit("onSubmit_All");
    };

    const cancelClick = () => {
      if (state.loading) {
        if (isAlionline.value || isOss.value) {
          state.canel_visible = true;
          // Modal.confirm({
          //   title: "提示",
          //   icon: createVNode(ExclamationCircleOutlined),
          //   content: "当前页面正在上传中，直接离开数据不会保存和更新",
          //   cancelText: "确认返回",
          //   okText: "留在当前页",
          //   onOk: async () => {},
          //   onCancel() {
          //     state.All_img = [];
          //     state.All_video = [];
          //     state.All_audio = [];
          //     state.Allin_up = true;
          //     state.duan_show = false;
          //     state.loading = false;
          //     state.is_over = true;
          //     emit("onSubmit_All");
          //   },
          //   style: {
          //     zIndex: 99999,
          //   },
          // });
        }
        // Modal.confirm({
        //   title: "提示",
        //   icon: createVNode(ExclamationCircleOutlined),
        //   content: "当前页面正在上传中，直接离开数据不会保存和更新",
        //   cancelText: "确认返回",
        //   okText: "留在当前页",
        //   onOk: async () => {},
        //   onCancel() {
        //     state.All_img = [];
        //     state.All_video = [];
        //     state.All_audio = [];
        //     state.Allin_up = true;
        //     state.duan_show = false;
        //     state.loading = false;
        //     state.is_over = true;
        //     emit("onSubmit_All");
        //   },
        //   style: {
        //     zIndex: 99999,
        //   },
        // });
      } else {
        state.All_img = [];
        state.All_video = [];
        state.All_audio = [];
        state.Allin_up = true;
        state.duan_show = false;
        state.loading = false;
        state.is_over = true;
        emit("onSubmit_All");
      }
    };

    const modelRef = reactive({
      name: [
        {
          text: "",
        },
      ],
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "请输入文案",
        },
      ],
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const del_item = (type) => {
      switch (type) {
        case "image":
          state.All_img = [];
          state.img_up_ing = false;
          state.typeArr = state.typeArr.filter((item) => item !== "image");
          state.queryData.files = state.queryData.files.filter(
            (item) => item.type.split("/")[0] !== "image"
          );
          break;
        case "video":
          state.All_video = [];
          state.video_up_ing = false;
          state.typeArr = state.typeArr.filter((item) => item !== "video");
          state.queryData.files = state.queryData.files.filter(
            (item) => item.type.split("/")[0] !== "video"
          );
          break;
        case "audio":
          state.All_audio = [];
          state.audio_up_ing = false;
          state.typeArr = state.typeArr.filter((item) => item !== "audio");
          state.queryData.files = state.queryData.files.filter(
            (item) => item.type.split("/")[0] !== "audio"
          );
          break;
      }
      if (
        state.All_img.length == 0 &&
        state.All_video.length == 0 &&
        state.All_audio.length == 0
      ) {
        console.log("回去");
        state.Allin_up = true;
        state.loading = false;
      }
    };

    const dynamicValidateForm = reactive({
      users: [
        {
          name: "",
        },
      ],
    });

    watch(
      () => props.visible,
      (val) => {
        if (!val) {
          dynamicValidateForm.users = [
            {
              name: "",
            },
          ];
          state.fileList = [];
          state.start = "";
          state.end = "";
        }
      }
    );

    watch(
      () => props.directory,
      (val) => {
        state.type = "Allin";
      },
      {
        immediate: true,
        deep: true,
      }
    );

    watch(
      () => props.type,
      (val) => {
        state.type = val;
      },
      {
        immediate: true,
        deep: true,
      }
    );

    // 页面摧毁的时候   停止轮训
    onUnmounted(() => {
      state.shouldContinuePolling = false; // 设置标志以停止轮询
      state.loading = false;
      state.img_up_ing = false;
      state.video_up_ing = false;
      state.audio_up_ing = false;
    });

    return {
      ...toRefs(state),
      cancelClick,
      beforeUpload,
      validateInfos,
      resetFields,
      modelRef,
      dynamicValidateForm,
      customRequest,
      saveFn,
      del_item,
      gocanel,
      canel_handleOk,
    };
  },
});
</script>

<style lang="less" scoped>
:deep(.ant-upload-list-picture-card-container) {
  margin: 0 8px 60px 0;
}

:deep(.ss-upload-list-picture-card-container) {
  margin-bottom: 35px;
}

.file-list {
  width: 102px;
  height: 120px;
  text-align: center;
  padding-bottom: 50px;
  margin-bottom: 10px;

  .file-content {
    width: 102px;
    height: 105px;
    background: #000;
    margin-bottom: 5px;
    cursor: pointer;
    position: relative;

    .file-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 102px;
      height: 105px;
      text-align: center;
      line-height: 138px;
      background: #000;
      opacity: 0;
      color: #fff;
    }

    &:hover {
      .file-mask {
        opacity: 0.3;
      }
    }
  }

  .file-name {
    width: 100%;
    display: flex;

    .text-ellipsis {
      width: 110px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}

.text-content {
  height: 320px;
  overflow: auto;
}

.footer {
  width: 100%;
  text-align: right;
  margin-top: 40px;
}

.Allin_W {
  width: 130px;
  position: relative;

  .Allin_WT {
    position: absolute;
    top: 50px;
    left: 45px;
    text-align: center;
  }
}

.Allin_B {
  width: 130px;
  margin-right: 20px;

  .All_icon {
    font-size: 130px;
    height: 140px;
    position: relative;

    .up_fin {
      position: absolute;
      bottom: -40px;
      right: 3px;
    }
  }
}

.progress_item {
  margin-left: 11px;
  width: 108px;
}

.Allin_T {
  color: #000;
  padding-left: 15px;
  width: 90%;
  display: flex;
  justify-content: space-between;

  .Allin_T_left {
    width: 83%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .Allin_T_right {
    width: 17%;
    z-index: 10;
  }
}

.yulan_box {
  display: flex;
}

:deep(.ss-upload-list-picture-card-container) {
  display: none !important;
}

:deep(.ss-upload) {
  // height: 150px !important;
  // width: 460px !important;
  // margin-top: 40px ;
}

.model_upload_text {
  font-size: 12px;
  color: #999;
}

.model_text {
  text-align: left;
  // margin-left: 20px;
}

.baseModel {
  :deep(.ss-modal-footer) {
    border-top: none !important;
  }
  :deep(.ss-modal-body) {
    padding-top: 30px !important;
  }
  :deep(.ss-modal) {
    width: 410px !important;
  }
}
</style>
